<?php
/**
 * 
 * 
 */
namespace app\api\controller;

use Think\Db;
use think\Cache;
use app\common\logic\UsersLogic;
class User extends ApiBase {

    protected $addressMdl;
    public function _initialize()
    {
        parent::_initialize();
        $this->addressMdl = model('Common/UserAddress');
    }

    /**
     * 个人中心页面
     */
    public function wxUserInfo(){
        $logic = new UsersLogic();
        $user  = $logic->get_info($this->user_id);
        if($user['status'] == -1){
            return $this->ajaxReturn([], 0, $user['msg']);
        }
        $user['countData']['status_0'] = $user['result']['waitPay']; //待付款数量
        $user['countData']['status_1'] = $user['result']['waitSend']; //待发货数量
        $user['countData']['status_2'] = $user['result']['waitReceive']; //待收货数量
        $user['countData']['status_3'] = $user['result']['finish']; //已完成数量
        $user['countData']['status_4'] = $user['result']['cancel']; //已取消数量

        //我的钱包
        $moneyLog = model('UserMoneyLog');
        $user['wallet']['user_money'] = $user['result']['user_money'];
        $user['wallet']['estimate'] = number_format($moneyLog->where(['user_id' => $this->user_id, 'is_estimate' => 1])->sum('money'), 2);
        $user['wallet']['distribut_money'] = $user['result']['distribut_money'];

        return $this->ajaxReturn($user);
    }

    //收货地址
    public function addressList(){
        $token = input('token');
        
        $where['user_id'] = $this->user_id;
        $list = $this->addressMdl->getAddressList($where);
        if (!$list) {
            return $this->ajaxReturn([],0,'失败');
        }
        foreach ($list as $key => $value) {
            $list[$key]['fullAddress'] = $value['fullAddress'];
            $list[$key]['province_name'] = $value['province_name'];
            $list[$key]['city_name'] = $value['city_name'];
            $list[$key]['district_name'] = $value['district_name'];
            $list[$key]['name'] = $value['consignee'];
            $list[$key]['detail'] = $value['address'];
        }
        return $this->ajaxReturn($list);
    }

    // 设置默认收货地址
    public function addressSetDefault(){
        $addressId  = input('address_id');
        $token      = input('token');
        
        $where['user_id'] = $this->user_id;
        $res = $this->addressMdl->where($where)->update(['is_default'=>0]);
        $where['address_id'] = $addressId;
        $res = $this->addressMdl->where($where)->update(['is_default'=>1]);
        $this->ajaxReturn($res);

    }

    // 删除地址
    public function addressDelete(){
        $addressId  = input('address_id');
        $token      = input('token');
        
        $where['user_id']    = $this->user_id;
        $where['address_id'] = $addressId;
        $res = $this->addressMdl->where($where)->delete();
        $this->ajaxReturn($res);
    }

    // 编辑地址
    public function addressSave(){
        $post = input('post.');
        $addressId         = $post['address_id'];
        $row['user_id']    = $this->user_id;
        $row['consignee']  = $post['name'];
        $row['province']   = $post['province_id'];
        $row['city']       = $post['city_id'];
        $row['district']   = $post['district_id'];
        $row['address']    = $post['detail'];
        $row['mobile']     = $post['mobile'];
        $row['is_default'] = $post['is_default']?$post['is_default']:0;
        if($addressId){
            $res = $this->addressMdl->editDataById($addressId,$row);
        }else{
            $res = $this->addressMdl->addData($row);
        }
        if ($res['code']) {
            return $this->ajaxReturn($res);
        }else{
            return $this->ajaxReturn([],0,$res['msg']);
        }
    }

    public function addressDetail(){
        $id = input('id');
        $where['user_id']    = $this->user_id;
        $where['address_id'] = $id;
        $res = $this->addressMdl->where($where)->find();
        if ($res) {
            $data['detail']      = $res['address'];
            $data['name']        = $res['consignee'];
            $data['province_id'] = $res['province'];
            $data['city_id']     = $res['city'];
            $data['district_id'] = $res['district'];
            $data['province']    = $res['province_name'];
            $data['city']        = $res['city_name'];
            $data['county']      = $res['district_name'];
            $data['mobile']      = $res['mobile'];
            $data['address_id']  = $res['address_id'];
            $data['is_default']  = $res['is_default'];
            return $this->ajaxReturn($data);
        }else{
            return $this->ajaxReturn([],0,'地址不存在');
        }
    }

    /* 省市区 */
    public function allAddress()
    {
        $data = null;
        if (Cache::tag('Api1Cache')->has('allAddress')) {
            $data = Cache::tag('Api1Cache')->get('allAddress');
            $data = unserialize($data);
        } else {
            $region = M('region')->where('id>0')->field('id,name,parent_id')->select();
            $k0 = 0;
            foreach ($region as $k => $v) {
                if ($v['parent_id'] == 0) {
                    $data[$k0]['name'] = $v['name'];
                    $data[$k0]['code'] = $v['id'];
                    //unset($region[$k]);
                    $i = 0;
                    foreach ($region as $k1 => $v1) {
                        if ($v1['parent_id'] == $v['id']) {
                            $data[$k0]['sub'][$i]['name'] = $v1['name']?$v1['name']:'';
                            $data[$k0]['sub'][$i]['code'] = $v1['id']?$v1['id']:'';
                            // unset($region[$k1]);

                            $j = 0;
                            foreach ($region as $k2 => $v2) {
                                if ($v2['parent_id'] == $v1['id']) {
                                    $data[$k0]['sub'][$i]['sub'][$j]['name'] = $v2['name']?$v2['name']:'';
                                    $data[$k0]['sub'][$i]['sub'][$j]['code'] = $v2['id']?$v2['id']:'';
                                    // unset($region[$k2]);
                                    $j++;
                                }
                            }
                            $i++;
                        }
                    }
                    $k0++;
                }
            }

            if (!empty($data)) {
                Cache::tag('Api1Cache')->set('allAddress', serialize($data),SHOP_CACHE_TIME);
                // $data = unserialize($data);
            }
        }
        // p($data);
        if (!empty($data)) {
            return $this->ajaxReturn($data);
        } else {
            return $this->ajaxReturn([],0,'失败');
        }

    }

    /**
     * 设置
     * type         0获取资料 1修改资料
     * truename     真实姓名
     * mobile       手机号码
     * sex          性别
     */
    public function setting()
    {
        if(!$this->user_id) return $this->ajaxReturn([], 0, '请先登录');
        $type = input('type', 0);
        $truename = input('truename', '');
        $mobile = input('mobile', '');
        $sex = input('sex', 1);
        $usersMdl = model('Users');
        if($type == 1){
            //检测提交过来的手机号码是不是别人已经注册过的
            $isset = $usersMdl->where(['user_id' => ['neq', $this->user_id], 'mobile' => $mobile])->count();
            if($isset)  return $this->ajaxReturn([], 0, '该号码已经被绑定');

            $token = buildToken($this->user_id);
            $res = $usersMdl->where('user_id', $this->user_id)->update([
                'truename'  => $truename,
                'mobile'    => $mobile,
                'sex'       => $sex,
                'token'     => $token
            ]);
            
            $this->user['mobile']    = $mobile;
            $this->user['token']     = $token;
            $this->user['sex']       = $sex;
            $this->user['truename']  = $truename;
            return $this->ajaxReturn($this->user);
        }

        $parent = $usersMdl->where('user_id', $this->user['tk_id'])->field('truename, nickname')->find();
        $data = [
            'truename'      => !empty($this->user['truename']) ? $this->user['truename'] : $this->user['nickname'],
            'mobile'        => $this->user['mobile'],
            'sex'           => $this->user['sex'] == 1 ? '男' : '女',
            'parent_name'   => !empty($parent['truename']) ? $parent['truename'] : $parent['nickname'],
        ];
        return $this->ajaxReturn($data);
    }

    public function decodeEncryptedData(){
        $iv  = I('iv');
        $encryptedData = I('encryptedData');
        $sessionKey    = $this->user['session_key'];
        $res = model('Common/User','logic')->decodesessionKey($sessionKey,$encryptedData,$iv,$appId=null);
        if ($res['code']==1) {
            $token  = buildToken($this->user_id);
            $result = $this->bindMobile($res['data']['phoneNumber'],$this->user_id,$token);
            if ($result['code']==1) {
                $this->user['mobile'] = $res['data']['phoneNumber'];
                $this->user['token']  = $token;
                return $this->ajaxReturn($this->user);
            }
            return $this->ajaxReturn([],0,$result['msg']);
        }
        return $this->ajaxReturn([],0,'绑定手机号失败');
    }

    /**
     * 绑定手机号
     * @return [type] [description]
     */
    public function bindMobile($mobile,$uid,$token){
        $usersMdl = model('Users');
        $isset    = $usersMdl->where(['user_id' => ['neq', $uid], 'mobile' => $mobile])->count();
        if($isset)  return ['code'=>0,'msg'=>'该号码已经被绑定'];
        
        $res      = $usersMdl->where('user_id', $uid)->update(['mobile'=> $mobile,'token'=> $token]);
        if ($res) {
            return ['code'=>1,'msg'=>'绑定成功'];
        }
        return ['code'=>0,'msg'=>'绑定失败'];
    }

    /**
     * 帐单列表
     * type         账单类型  0所有 1支出 2收入 3提现（包括提现手续费）
     * searchTime   筛选的月份 2018-08
     */
    public function myMoneyLog()
    {

        $type = input('type', 0);
        $page = input('page', 1);
        $searchTime = input('searchTime');
        $num = 10;
        $where['user_id'] = $this->user_id;
        switch($type){
            case 1:
                $where['money'] = ['lt', 0];
                break;
            case 2:
                $where['money'] = ['gt', 0];
                break;
            case 3:
                $where['type'] = ['in', [4, 5]];
                break;
        }
        //时间区间筛选
        if(!empty($searchTime)){
            $startTime = strtotime($searchTime);
            $endTime = strtotime('+1 month', $startTime);
            $where['create_time'] = ['between' , [$startTime, $endTime]];
        }
        //p($where);
        $list = model('UserMoneyLog')->getList($where, $page, $num);
        if(empty($list))    return $this->ajaxReturn([], 0, '没有数据了');

        foreach ($list as $key => $value) {
            $list[$key]['add_time'] = $value['create_time'];
        }
        return $this->ajaxReturn($list);

    }

    //账单详情
    public function moneyLogDetail()
    {
        $id = input('id');
        $data = model('UserMoneyLog')->where(['id' => $id, 'user_id' => $this->user_id])->find();
        if(empty($data)){
            return $this->ajaxReturn([], 0, '参数错误');
        } else {
            return $this->ajaxReturn($data);
        }
    }

    /**
     * 我的团队
     */
    public function myTeam()
    {
        //model('UserMoneyLog')->addData(47, 100, 2, '201808089999999999', 0, ['order_sn' => '201808089999999999']);
        $page = input('page', 1);
        $num = 10;
        $usersMdl = model('Users');
        $list = $usersMdl->getSonList($this->user_id, $page, $num);
        $data = [];
        if(empty($list)){
            $this->ajaxReturn([], 0, '没有数据了');
        } else {
            foreach($list as $k => $v){
                $data[$k] = [
                    'nickname'          => $v['nickname'],
                    'reg_time'          => date('Y-m-d', $v['reg_time']),
                    'head_pic'          => manageImgUrl($v['head_pic']),
                    'distribut_money'   => $v['distribut_money'],
                    'countSon'          => $usersMdl->where(['tk_id' => $v['user_id']])->count()
                ];
            }
            $countSon = $usersMdl->where(['tk_id' => $this->user_id])->count();
            $this->ajaxReturn([
                'countSon' => $countSon,
                'data' => $data,
            ]);
        }

    }

    /**
     * 设置支付密码
     * password     支付密码
     * password1    确认支付密码
     */
    public function setPayPassword()
    {
        $password = input('post.password', '');
        $password1 = input('post.password1', 'a');
        if ($password != $password1)
            return $this->ajaxReturn([], 0, '两次输入的密码不一致');

        model('Users')->where('user_id', $this->user_id)->update(['paypwd' => $password]);
        return $this->ajaxReturn([], 1, '修改成功');
    }

    /**
     * 提现申请提交
     */
    public function withdrawals(){

        if (IS_POST) {

            $data = I('post.');
            $data['user_id'] = $this->user_id;
            $data['create_time'] = time();
            $cash = tpCache('cash');
            // if(encrypt($data['paypwd']) != $this->user['paypwd']){
            //     return $this->ajaxReturn([],0,'支付密码错误');
            // }
            if ($data['money'] > $this->user['user_money']) {
                return $this->ajaxReturn([],0,'本次提现余额不足');
            } 
            if ($data['money'] <= 0) {
                return $this->ajaxReturn([],0,'提现额度必须大于0');
            }

            // 统计所有0，1的金额
            $status = ['in','0,1'];   
            $total_money = Db::name('withdrawals')->where(array('user_id' => $this->user_id, 'status' => $status))->sum('money');
            if ($total_money + $data['money'] > $this->user['user_money']) {
                return $this->ajaxReturn([],0,'您有提现申请待处理，本次提现余额不足');
            }

            if ($cash['cash_open'] == 1) {
                $taxfee =  round($data['money'] * $cash['service_ratio'] / 100, 2);
                // 限手续费
                if ($cash['max_service_money'] > 0 && $taxfee > $cash['max_service_money']) {
                    $taxfee = $cash['max_service_money'];
                }
                if ($cash['min_service_money'] > 0 && $taxfee < $cash['min_service_money']) {
                    $taxfee = $cash['min_service_money'];
                }
                if ($taxfee >= $data['money']) {
                    return $this->ajaxReturn([],0,'手续费超过提现额度了！');
                }
                $data['taxfee'] = $taxfee;


                // 每次限提现额度
                if ($cash['min_cash'] > 0 && $data['money'] < $cash['min_cash']) {
                    return $this->ajaxReturn([],0,'每次最少提现额度' . $cash['min_cash']);
                }
                if ($cash['max_cash'] > 0 && $data['money'] > $cash['max_cash']) {
                    return $this->ajaxReturn([],0,'每次最多提现额度' . $cash['max_cash']);
                }

                // 今天限总额度
                if ($cash['count_cash'] > 0) {
                    $status = ['in','0,1,2,3'];
                    $create_time = ['gt',strtotime(date("Y-m-d"))];
                    $total_money2 = Db::name('withdrawals')->where(array('user_id' => $this->user_id, 'status' => $status, 'create_time' => $create_time))->sum('money');
                    if (($total_money2 + $data['money'] > $cash['count_cash'])) {
                        $total_money = $cash['count_cash'] - $total_money2;
                        if ($total_money <= 0) {
                            return $this->ajaxReturn([],0,"你今天累计提现额为{$total_money2},不能再提现了.");
                        } else {
                            return $this->ajaxReturn([],0,"你今天累计提现额为{$total_money2}，最多可提现{$total_money}账户余额.");
                        }
                    }
                }
                // 今天限申请次数
                if ($cash['cash_times'] > 0) {
                    $total_times = Db::name('withdrawals')->where(array('user_id' => $this->user_id, 'status' => $status, 'create_time' => $create_time))->count();
                    if ($total_times >= $cash['cash_times']) {
                        return $this->ajaxReturn([],0,"今天申请提现的次数已用完");
                    }
                }
            }else{
                $data['taxfee'] = 0;
            }
            $data['flow_id']  = date('YmdHis').rand(100000,999999);
            $id = M('withdrawals')->insertGetId($data);
            if ($id) {
                // 余额变动记录
                $moneyLogMdl = model('Common/UserMoneyLog');
                $moneyLogMdl->addData($this->user_id, -$data['money']+$data['taxfee'], 4, $data['flow_id'], 0, ['withdrawals_id'=>$data['id'],'user_id'=>$this->user_id]);
                if ($data['taxfee']>0) {
                    $moneyLogMdl->addData($this->user_id, -$data['taxfee'], 5, $data['flow_id'], 0, ['withdrawals_id'=>$data['id'],'user_id'=>$this->user_id]);
                }
                return $this->ajaxReturn([],1,'已提交申请');
            } else {
                return $this->ajaxReturn([],0,"提交失败,联系客服!");
            }


            //获取用户绑定openId
            // $oauthUsers = M("OauthUsers")->where(['user_id'=>$this->user_id, 'oauth_child'=>'mp'])->find();
            // $openid = $oauthUsers['openid'];

            // $user_extend=Db::name('user_extend')->where('user_id='.$this->user_id)->find();

            // $this->assign('user_extend',$user_extend);
            // $this->assign('openid',$openid);    //用户绑定的微信openid
            // $this->assign('cash_config', tpCache('cash'));//提现配置项
            // $this->assign('user_money', $this->user['user_money']);    //用户余额
        }
        $data['cash_config'] = tpCache('cash');
        $data['user_money']  = $this->user['user_money'];
        return $this->ajaxReturn($data,1,'请求成功');

    }

    //提现账单列表
    public function withdrawalsList()
    {
        $page = input('page', 1);
        $searchTime = input('searchTime');

        //时间区间筛选
        if(!empty($searchTime)){
            $startTime = strtotime($searchTime);
            $endTime = strtotime('+1 month', $startTime);
            $where['create_time'] = ['between' , [$startTime, $endTime]];
        }
        $where['user_id'] = $this->user_id;
        $list = model('Withdrawals')->getList($where, $page);
        if(empty($list)){
            return $this->ajaxReturn([],0,'没有数据了');
        } else {
            $total_money = 0;
            $rebate_money = 0;
            foreach ($list as $key => $value) {
                $list[$key]['add_time'] = $value['create_time'];
                $total_money  += $value['money'];
                $rebate_money += $value['taxfee'];
            }
            $data['list'] = $list;
            $data['total_money']  = number_format($total_money,2);
            $data['rebate_money'] = number_format($rebate_money,2);
            return $this->ajaxReturn($data);
        }

    }

    public function withdrawalsDetail(){
        $id = I('id');
        $where['id']      = $id;
        $where['user_id'] = $this->user_id;
        $Withdrawals      = model('Common/Withdrawals');
        $result = $Withdrawals->getDetail($where);  //提现记录
        if ($result) {
            $result['status_des']  = $result['status_name'];
            $result['actureMoney'] = $result['money']-$result['taxfee'];
            $result['check_time']  = $result['check_time']>0?date('Y-m-d H:i:s',$result['check_time']):0;
            $result['pay_time']    = $result['pay_time']>0?date('Y-m-d H:i:s',$result['pay_time']):0;
            return $this->ajaxReturn($result);
        }
        return $this->ajaxReturn([],0,'数据不存在');

    }

    public function userQrcode(){
        $imageName = date("His",time())."_".rand(1111,9999).'.jpg';
        // dump(2);
        $path      = "public/static/qrcode";
        if (!is_dir($path)){ //判断目录是否存在 不存在就创建
          mkdir($path,0777,true);
        }
        $savePath  = $path."/". $imageName; //图片名字

        $qrcodeMdl = model('Common/UsersQrcodeLogic','logic');
        $result = $qrcodeMdl->get_wxapp_qrcode($this->user_id,$savePath);
        // p($result);
        if ($result['code']==1) {
            return $this->ajaxReturn(SITE_URL."/".$savePath);
        }
        return $this->ajaxReturn([],0,"失败");
    }
}